package com.wangwei.modules.utils.db

import com.wangwei.modules.servlet.spring.Component
import java.sql.Connection
import java.sql.Driver
import java.sql.DriverManager
import java.sql.ResultSet
import java.sql.ResultSetMetaData
import java.sql.Statement
import java.util.ArrayList
import java.util.HashMap

enum class DBType(var driver: String) {
	ORACLE("oracle.jdbc.driver.OracleDriver"), SQLSERVER("com.microsoft.sqlserver.jdbc.SQLServerDriver"), MYSQL("com.mysql.jdbc.Driver")
	;

}


open class DBHelpar(val dbType: DBType, val conn: String, val uid: String, val pwd: String) {


	fun getConnection(): Connection {
		val driver = Class.forName(dbType.driver).newInstance()
		if (driver is Driver) {
			var conn = DriverManager.getConnection(conn, uid, pwd);
			return conn
		}
		throw Exception("连接无法创建")
	}

	fun update(sql: String): Int {
		var conn: Connection? = null
		var st: Statement? = null
		try {
			conn = getConnection();
			st = conn.createStatement();
			return st.executeUpdate(sql);
		} catch (e: Exception) {
			throw  Exception(e.toString());
		} finally {
			try {
				st?.close();
			} catch (e: Exception) {
			}
			try {
				conn?.close();
			} catch (e: Exception) {
			}
		}
	}


	fun getAll(sql: String): ArrayList<HashMap<String, String>> {
		var rs: ResultSet? = null;
		var st: Statement? = null;
		var conn: Connection? = null;
		var fieldname: ArrayList<String>? = null;
		var all: ArrayList<HashMap<String, String>> = arrayListOf<HashMap<String, String>>()
		try {
			conn = getConnection();
			st = conn.createStatement();
			rs = st.executeQuery(sql);
			var rsmd: ResultSetMetaData? = null;
			while (rs.next()) {
				if (rsmd == null) {//第一次，初始列名
					rsmd = rs.getMetaData();
					fieldname = arrayListOf<String>();

					for (i in 0..rsmd.getColumnCount() - 1) {
						fieldname.add(rsmd.getColumnLabel(i + 1));
					}
				}
				var map = hashMapOf<String, String>();
				if (fieldname != null) {
					for (i in 0..fieldname.size - 1) {
						map.put(fieldname.get(i), rs.getString(fieldname.get(i)));
					}
				}
				all.add(map);
			}
		} finally {
			try {
				rs?.close();
			} catch (e: Exception) {
			}
			try {
				st?.close();
			} catch (e: Exception) {
			}
			try {
				conn?.close();
			} catch (e: Exception) {
			}

		}
		return all;
	}


}

@Component
class MySqlTestDB : DBHelpar {
	constructor() :
			super(DBType.MYSQL, "jdbc:mysql://192.168.31.4/alauda_development?useUnicode=true&characterEncoding=UTF-8", "root", "");

}







